package com.skywork.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Minutes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import com.skywork.controller.exception.RestException;
import com.skywork.domain.Channel;



public class SignUtil {

	private static Logger LOGGER = LoggerFactory.getLogger(SignUtil.class);

	public static boolean checkSignature(String body, Channel channel, Long timestamp, String sign) {
		LOGGER.info("System time:{}",System.currentTimeMillis());
		DateTime clientDate = new DateTime(timestamp).withZone(DateTimeZone.forID("America/New_York")).toDateTime();
		int minutes = Minutes.minutesBetween(new DateTime(),clientDate).getMinutes();
		LOGGER.info("时间差:{}",minutes);
		if(minutes<-10||minutes>10) {
			throw new RestException(HttpStatus.BAD_REQUEST, "timestamp Error");
		}
		
		StringBuffer signStr = new StringBuffer();
		if (StringUtils.isBlank(body)) {
			body = "";
		}

		signStr.append(body).append(channel.getPassword()).append(timestamp);
		String md5 = DigestUtils.md5Hex(signStr.toString());
		LOGGER.info("\nbody:{};\ntimestamp:{};\nsign:{};\nmd5:{}", body, timestamp, sign, md5);

		return md5.equals(sign);
	}
}
